//
//  NotificationApiController.java
//  FeOA
//
//  Created by LuTH on 2012-4-1.
//  Copyright 2012 flyrise. All rights reserved.
//

package com.thinkgem.jeesite.androidpn.server.console.api;

import com.thinkgem.jeesite.androidpn.server.console.vo.MessageVO;
import com.thinkgem.jeesite.androidpn.server.util.Config;
import com.thinkgem.jeesite.androidpn.server.xmpp.push.NotificationManager;
import com.thinkgem.jeesite.androidpn.server.xmpp.session.ClientSession;
import com.thinkgem.jeesite.androidpn.server.xmpp.session.SessionManager;
import com.thinkgem.jeesite.common.result.CallResult;
import com.thinkgem.jeesite.common.result.StatusCode;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.notify.entity.NotiMessage;
import com.thinkgem.jeesite.modules.notify.service.NotiMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Controller
@RequestMapping(value = "/push/api/notify")
public class NotificationApiController extends BaseController {

	private NotificationManager notificationManager;

	@Autowired
	private NotiMessageService notiMessageService;

	public NotificationApiController() {
		notificationManager = new NotificationManager();
	}

	@RequestMapping(value = {"list",""})
	public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();
		// mav.addObject("list", null);
		mav.setViewName("notification/form");
		return mav;
	}

	@RequestMapping(value = "send")
	@ResponseBody
	public CallResult send(HttpServletRequest request,
						   HttpServletResponse response, @RequestBody MessageVO msg) throws Exception {
//		String broadcast = ServletRequestUtils.getStringParameter(request,
//				"broadcast", "Y");
//		String username = ServletRequestUtils.getStringParameter(request,
//				"username");
//		String title = ServletRequestUtils.getStringParameter(request, "title");
//		String message = ServletRequestUtils.getStringParameter(request,
//				"message");
//		String uri = ServletRequestUtils.getStringParameter(request, "uri");
        NotiMessage message = new NotiMessage();
        message.setMsgContent(msg.getMessage());
        message.setPushPlatform("android");
		message.setMsgTitle(msg.getTitle());
		message.setAppedition(msg.getAppedition());
		message.setAppid(msg.getAppid());
		if ("Y".equals(msg.getBroadcast())) {
			message.setPushType("broadcast");
		} else {
			message.setPushType("0");
		}

        notiMessageService.save(message);
//
		String apiKey = Config.getString("apiKey", "");
		logger.debug("apiKey=" + apiKey);

		if (msg.getBroadcast().equalsIgnoreCase("Y")) {
            notificationManager.sendBroadcast(apiKey, msg.getTitle(), msg.getMessage(), msg.getUri(), message.getId(), msg.getAppid(), msg.getAppedition());
        } else {
            notificationManager.sendNotifcationToUser(apiKey, msg.getUsername(), msg.getTitle(), msg.getMessage(), msg.getUri(), message.getId(), msg.getAppid(), msg.getAppedition());
        }
        return new CallResult(true, message.getId(), StatusCode.SUCCESS, "success");
//		response.getWriter().print("{\"result\":\"0\",\"description\":\"success\"}");
//		ModelAndView mav = new ModelAndView();
//		mav.setViewName("redirect:notification.do");
//		return mav;
	}

	@RequestMapping(value = "getSeesion")
	@ResponseBody
	public CallResult getSeesion(HttpServletRequest request,
								 HttpServletResponse response, @RequestBody MessageVO msg) throws Exception {
		Collection<ClientSession> sessions = SessionManager.getInstance().getSessions();

		List<String> usernameList = new ArrayList<String>();
		for (ClientSession session : sessions) {
			if (StringUtils.isEmpty(msg.getAppid())) {
				usernameList.add(session.getUsername());
			} else {
				if (session.getAuthToken().getAppid().equals(msg.getAppid())) {
					usernameList.add(session.getUsername());
				}
			}
		}
		return new CallResult(true, usernameList, StatusCode.SUCCESS, "success");
	}

}
